#!/bin/sh

# webpanel script version v0.1

. ./webpanel.conf

OPTION=$1
DOMAIN=$2

main()
{
	if [ "x$DOMAIN" = "x" ]; then
        	usage
       		exit 1
	fi

	case $OPTION in
        	"add_vhost")    add_vhost;;
        	"ADD_VHOST")    add_vhost;;
        	"add_db")       add_db;;
        	"ADD_DB")       add_db;;
        	*)              echo "Incorrect parameter \"$OPTION\"";usage;exit 1;;
	esac
}

usage()
{
	echo -e ""
	echo -e "webpanel script by OpenQuest"
	echo -e ""
	echo -e "Usage: webpanel.sh ADD_VHOST|ADD_BD DOMAIN"
	echo -e ""
}

add_vhost()
{
	if [ -e ${VHOSTS_DIR}/${DOMAIN} ] ; then
		echo "Domain already configured.";
		exit 1;
	else
		mkdir -m$MODE $VHOSTS_DIR/$DOMAIN
		mkdir -m$MODE $VHOSTS_DIR/$DOMAIN/files
		mkdir -m$MODE $VHOSTS_DIR/$DOMAIN/www
		mkdir -m$MODE $VHOSTS_DIR/$DOMAIN/www/files
		mkdir -m$MODE $VHOSTS_DIR/$DOMAIN/www/sites
		mkdir -m$MODE $VHOSTS_DIR/$DOMAIN/www/sites/default
		
		#mkdir -m$MODE $VHOSTS_DIR/$DOMAIN/www/themes
		ln -s $DRUPAL_INSTALL_DIR/themes $VHOSTS_DIR/$DOMAIN/www/
		
		chown -R $OWNER $VHOSTS_DIR/$DOMAIN
		ln -s $DRUPAL_INSTALL_DIR/cron.php $VHOSTS_DIR/$DOMAIN/www/
		ln -s $DRUPAL_INSTALL_DIR/includes $VHOSTS_DIR/$DOMAIN/www/
		ln -s $DRUPAL_INSTALL_DIR/index.php $VHOSTS_DIR/$DOMAIN/www/
		ln -s $DRUPAL_INSTALL_DIR/install.php $VHOSTS_DIR/$DOMAIN/www/
		ln -s $DRUPAL_INSTALL_DIR/misc $VHOSTS_DIR/$DOMAIN/www/
		ln -s $DRUPAL_INSTALL_DIR/modules $VHOSTS_DIR/$DOMAIN/www/
		ln -s  $DRUPAL_INSTALL_DIR/sites/all $VHOSTS_DIR/$DOMAIN/www/sites/
		ln -s $DRUPAL_INSTALL_DIR/profiles $VHOSTS_DIR/$DOMAIN/www/
		ln -s $DRUPAL_INSTALL_DIR/robots.txt $VHOSTS_DIR/$DOMAIN/www/
		ln -s $DRUPAL_INSTALL_DIR/xmlrpc.php $VHOSTS_DIR/$DOMAIN/www/
		cp -p $DRUPAL_INSTALL_DIR/sites/default/settings.php $VHOSTS_DIR/$DOMAIN/www/sites/default
	fi
}

add_db()
{
	db_exists=`echo "exit" | mysql -D${DOMAIN//./_} 2>&1 | wc -l`
	if [ $db_exists = 0 ]; then
		echo "Database already exists."
		exit 1
	fi
	RPASSW=`./randompassword.sh`

	EXPR="CREATE DATABASE ${DOMAIN//./_};CREATE USER ${DOMAIN//./_}@'localhost' IDENTIFIED BY '${RPASSW}';GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, DROP, INDEX, ALTER, CREATE TEMPORARY TABLES, LOCK TABLES ON \`${DOMAIN//./_}\`.* TO '${DOMAIN//./_}'@'localhost';"
	echo "mysql root password:"
	read ROOTPASS
	if [ -z $ROOTPASS ]; then
		mysql -u root -e "$EXPR"
	else	
		mysql -u root -p$ROOTPASS -e "$EXPR"
	fi
	echo "Created database '${DOMAIN//./_}' and user '${DOMAIN//./_}' with password '$RPASSW'"
}

main
exit 0

